import { useState } from 'react';
import './ProcessFlow.css';

const ProcessFlow = ({ nodeFlow, isStreaming }) => {
  const [isExpanded, setIsExpanded] = useState(false);
  
  if (!nodeFlow || nodeFlow.length === 0) {
    return null;
  }

  const getNodeStatus = (node) => {
    if (node.status === 'completed') return 'completed';
    if (node.status === 'processing') return 'processing';
    return 'pending';
  };

  const getNodeIcon = (status) => {
    switch (status) {
      case 'completed': return '✅';
      case 'processing': return '⏳';
      default: return '⏸️';
    }
  };

  const getNodeDescription = (node) => {
    switch (node.name) {
      case 'SemanticRouterNode':
        return `数据库: ${node.data?.databaseName || '未知'}`;
      case 'IntentIdentificationNode':
        return `业务类型: ${node.data?.businessTypes?.join(', ') || '未知'}`;
      case 'GetTableNamesNode':
        return `涉及表: ${node.data?.tableNames?.length || 0} 个`;
      case 'SqlExecuteNode':
        return `查询结果: ${node.data?.data?.records?.length || 0} 条记录`;
      case 'ChartGenerationNode':
        return '图表已生成';
      default:
        return node.description || '处理中...';
    }
  };

  const completedCount = nodeFlow.filter(node => node.status === 'completed').length;
  const totalCount = nodeFlow.length;
  
  // 如果流程已结束（没有正在处理的节点且isStreaming为false），确保显示正确的完成状态
  const isFlowCompleted = !isStreaming && completedCount === totalCount && totalCount > 0;
  
  // 获取当前正在处理的节点
  const currentProcessingNode = nodeFlow.find(node => node.status === 'processing');
  
  // 获取要显示的步骤（折叠时显示当前处理节点，如果没有处理中的节点则显示最后一个已完成的节点，展开时显示所有）
  const stepsToShow = isExpanded ? nodeFlow : (
    currentProcessingNode ? [currentProcessingNode] : 
    (nodeFlow.length > 0 ? [nodeFlow[nodeFlow.length - 1]] : [])
  );

  return (
    <div className="process-flow">
      <div className="flow-header">
        <div className="flow-title">
          <span className="flow-icon">⚙️</span>
          <span>处理流程</span>
        </div>
        <div className="flow-progress">
          {isFlowCompleted ? (
            <span className="completed-indicator">✅ 已完成</span>
          ) : (
            <>
              {completedCount} / {totalCount}
              {isStreaming && <span className="processing-indicator">处理中...</span>}
            </>
          )}
        </div>
        <button 
          className="toggle-btn"
          onClick={() => setIsExpanded(!isExpanded)}
          title={isExpanded ? '折叠' : '展开'}
        >
          {isExpanded ? '▼' : '▶'}
        </button>
      </div>
      
      {stepsToShow.length > 0 && (
        <div className="flow-steps">
          {stepsToShow.map((node, index) => {
            const originalIndex = nodeFlow.findIndex(n => n.name === node.name);
            return (
              <div key={node.name} className={`flow-step ${getNodeStatus(node)}`}>
                <div className="step-number">{originalIndex + 1}</div>
                <div className="step-icon">
                  {getNodeIcon(getNodeStatus(node))}
                </div>
                <div className="step-content">
                  <div className="step-name">{node.displayName}</div>
                  <div className="step-desc">{getNodeDescription(node)}</div>
                </div>
                <div className="step-time">{node.timestamp}</div>
                {isExpanded && originalIndex < nodeFlow.length - 1 && <div className="step-connector"></div>}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default ProcessFlow;
